//
//  Parameters.swift
//  ExRequest
//
//  Created by 王渊鸥 on 2018/8/10.
//  Copyright © 2018 WangYuanOu. All rights reserved.
//

import Foundation

public func ex_parameters(params:[String:Any]) -> String {
    return params.map { (kv) -> String in
        let key = kv.key.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) ?? kv.key
        let value = "\(kv.value)".addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) ?? "\(kv.value)"
        return "\(key)=\(value)"
    }.joined(separator: "&")
}

public enum BoundryValue {
    case text(String)
    case file(Data)
}

public func ex_boundry(boundry:String, values:[String:BoundryValue]) -> Data {
    let result:NSMutableData = NSMutableData()
    
    for item in values {
        switch item.value {
        case .text(let text):
            let leadString = "\n--\(boundry)"
                + "\nContent-Disposition:form-data;name=\"\(item.key)\"\n"
                + "\n\(text)"
            
            if let data = leadString.data(using: String.Encoding.utf8) {
                result.append(data)
            }
        case .file(let data):
            let leadString = "\n--\(boundry)"
                + "\nContent-Disposition:form-data;name=\"file\";filename=\"\(item.key)\""
                + "\nContent-Type:application/octet-stream"
                + "\nContent-Transfer-Encoding:binary\n\n"
            
            if let lead = leadString.data(using: String.Encoding.utf8) {
                result.append(lead)
            }
            result.append(data)
        }
    }
    
    let endString = "\n--\(boundry)--"
    if let data = endString.data(using: String.Encoding.utf8) {
        result.append(data)
    }
    
    return result as Data
}
